接下來要設置資料庫關聯
假設一張User表的model長這樣
public partial class User
{
public int Id { get; set; }
public string? name { get; set; }
public string password { get; set; }
public int adress_id { get; set; }
public Adress Adress { get; set; }
}
還有一張Adress表長這樣
public partial class Adress
{
public int Id { get; set; }
public string? name { get; set; }
public User User { get; set; }
}
然後資料庫上下文的OnModelCreating方法就要新增一段
modelBuilder.Entity<User>()
.HasOne(p => p.Adress)
.WithOne(pc => pc.User)
.HasForeignKey<User>(p => p.adress_id);
這樣子就是一個一對一連接,由User的adress_id欄位對應Adress表的id欄位
User表的model
public partial class User
{
public int Id { get; set; }
public string? name { get; set; }
public string password { get; set; }
public int adress_id { get; set; }
public ICollection<Adress> Adress { get; set; }
}
Adress表的Model
public partial class Adress
{
public int Id { get; set; }
public string? name { get; set; }
public User User { get; set; }
}
然後資料庫上下文的OnModelCreating方法就要新增一段
modelBuilder.Entity<User>()
.HasMany(p => p.Adress)
.WithOne(pc => pc.User)
.HasForeignKey(p => p.adress_id);
User表的model
public partial class User
{
public int Id { get; set; }
public string? Name { get; set; }
public string Password { get; set; }
public ICollection<UserAddress> UserAddresses { get; set; }
}
Adress表的Model
public partial class Address
{
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<UserAddress> UserAddresses { get; set; }
}
多對多關聯需要一張中間表,所以我們新增一張中間表UserAddress
public class UserAddress
{
public int UserId { get; set; }
public User User { get; set; }
public int AddressId { get; set; }
public Address Address { get; set; }
}
然後資料庫上下文要設定三個
modelBuilder.Entity<UserAddress>()
.HasKey(ua => new { ua.UserId, ua.AddressId });
modelBuilder.Entity<UserAddress>()
.HasOne(ua => ua.User)
.WithMany(u => u.UserAddresses)
.HasForeignKey(ua => ua.UserId);
modelBuilder.Entity<UserAddress>()
.HasOne(ua => ua.Address)
.WithMany(a => a.UserAddresses)
.HasForeignKey(ua => ua.AddressId);
上面的資料庫關聯設定好之後,記得在下一次前面用過的新增資料庫遷移檔案和更新資料庫的指令,把資料庫更新喔!